package com.sjy.imagepicker;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.sjy.imagepicker.adapter.ImageAdapter;
import com.sjy.imagepicker.bean.FolderBean;
import com.sjy.imagepicker.widget.PicDirsWindow;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhang on 2017/4/8.
 */

public class GalleryActivity extends AutoLayoutActivity {
    public static final String IMAGE_COUNT_MAX = "IMAGE_COUNT_MAX";
    public static final String IMAGE_PATH_LIST = "IMAGE_PATH_LIST";
    public static final int REQUEST_IMAGE_PICK = 101;
    private static final int REQUEST_PERMISSION_READ_IMAGE_FOLDERS = 201;
    private int mImageCountMax;
    private ArrayList<String> mPickedImagePaths;
    private GridView mGv;
    private TextView mTvComplete;
    private ProgressDialog mProgressDialog;
    private PicDirsWindow mPicDirsWindow;
    private ImageAdapter mImageAdapter;
    private TextView mTvTitle;
    private List<String> mChildImagePaths;
    private ImageView mIvState;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        Intent intent = getIntent();
        mImageCountMax = intent.getIntExtra(IMAGE_COUNT_MAX, 0);
        mPickedImagePaths = intent.getStringArrayListExtra(IMAGE_PATH_LIST);
        initView();
        initData();
    }


    private void initView() {
        mGv = (GridView) findViewById(R.id.gv);
        mTvComplete = (TextView) findViewById(R.id.tv_complete);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvComplete.setText("完成（" + mPickedImagePaths.size() + "/" + mImageCountMax + ")");
        mIvState = (ImageView) findViewById(R.id.iv_state);
    }

    private void initData() {

        mImageAdapter = new ImageAdapter(this, mPickedImagePaths, mImageCountMax);
        mImageAdapter.setOnImagePickedListener(new ImageAdapter.OnImagePickedListener() {
            @Override
            public void onImagePicked() {
                mTvComplete.setText("完成（" + mPickedImagePaths.size() + "/" + mImageCountMax + ")");
            }
        });
        mImageAdapter.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(GalleryActivity.this, ImageViewerActivity.class);
                intent.putExtra(ImageViewerActivity.CURRENT_POS, position);
                intent.putStringArrayListExtra(ImageViewerActivity.IMAGE_PATH_LIST, (ArrayList<String>) mChildImagePaths);
                startActivity(intent);
            }

        });
        mGv.setAdapter(mImageAdapter);
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "存储卡不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

        if (result == PackageManager.PERMISSION_GRANTED) {
            readImageFolders();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_READ_IMAGE_FOLDERS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_READ_IMAGE_FOLDERS) {
            int result = grantResults[0];
            if (result == PackageManager.PERMISSION_GRANTED) {
                readImageFolders();
            } else if (result == PackageManager.PERMISSION_DENIED) {
                Log.d("test", "readImageFolders: permission deny");


            }
        }
    }

    private void readImageFolders() {
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
        getImageFolders().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<FolderBean>>() {


                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(GalleryActivity.this, "获取图片失败", Toast.LENGTH_SHORT).show();
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onNext(List<FolderBean> folderList) {
                        initPicDirsWindow(folderList);
                        FolderBean folderBean = folderList.get(0);
                        mChildImagePaths = folderBean.getChildImagePaths();
                        mImageAdapter.setImgPaths(mChildImagePaths);
                        mTvTitle.setText(folderBean.getName());
                        mProgressDialog.dismiss();
                    }
                });

    }

    private void initPicDirsWindow(List<FolderBean> mFolderBeans) {
        mPicDirsWindow = new PicDirsWindow(this, mFolderBeans);
        mPicDirsWindow.setOnDismissListener(new PopupWindow.OnDismissListener(){

            @Override
            public void onDismiss() {
                mIvState.setImageResource(R.mipmap.icon_down);
            }
        });

        mPicDirsWindow.setOnDirSelectedListener(new PicDirsWindow.OnDirSelectedListener() {
            @Override
            public void onDirSelected(FolderBean folderBean) {
                mChildImagePaths = folderBean.getChildImagePaths();
                mImageAdapter.setImgPaths(mChildImagePaths);
                mTvTitle.setText(folderBean.getName());
                mPicDirsWindow.dismiss();

            }
        });
    }

    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();
        }
        else if (i == R.id.tv_complete) {
            Intent data = new Intent();
            data.putStringArrayListExtra(IMAGE_PATH_LIST, mPickedImagePaths);
            setResult(RESULT_OK, data);
            finish();

        } else if (i == R.id.tv_title) {
            mPicDirsWindow.showAsDropDown((View) view.getParent().getParent(), 0, 0);
            mIvState.setImageResource(R.mipmap.icon_up);
        }
    }

    private Observable<List<FolderBean>> getImageFolders() {
        Uri mImgUrl = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = getContentResolver().query(mImgUrl,
                new String[]{MediaStore.Images.Media.DATA},
                null, null,
                MediaStore.Images.Media.DATE_MODIFIED + " desc");
        final List<FolderBean> folderList = new ArrayList<>();
        FolderBean allImage = null;
        Map<String, FolderBean> parentFolderMap = new LinkedHashMap<>();
        while (cursor.moveToNext()) {
            String imagePath = cursor.getString(0);
            if(imagePath.endsWith(".gif")){
                continue;
            }
            //Log.e("test", "imagePath: "+imagePath);
            if (allImage == null) {

                allImage = new FolderBean();
                allImage.setName("全部图片");
                allImage.setFirstImgPath(imagePath);
                parentFolderMap.put("全部图片", allImage);
                folderList.add(allImage);
            }
            allImage.getChildImagePaths().add(imagePath);

            File parentFile = new File(imagePath).getParentFile();
            if (parentFile == null) {
                continue;
            }
            String parentPath = parentFile.getAbsolutePath();
            FolderBean bean = null;
            if (parentFolderMap.keySet().contains(parentPath)) {
                parentFolderMap.get(parentPath).getChildImagePaths().add(imagePath);
                continue;
            } else {
                bean = new FolderBean();
                bean.setName(parentFile.getName());
                bean.setFirstImgPath(imagePath);
                bean.getChildImagePaths().add(imagePath);
                parentFolderMap.put(parentPath, bean);

            }

            folderList.add(bean);

        }

        return Observable.create(new Observable.OnSubscribe<List<FolderBean>>() {

            @Override
            public void call(Subscriber<? super List<FolderBean>> subscriber) {
                subscriber.onNext(folderList);
            }
        });

    }


}
